package com.example.demo.controller;

import com.example.demo.common.PasswordTool;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    //用户登录
    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest req) {
        User user = userMapper.login(username);
        if (user == null || !PasswordTool.decrypt(password, user.getPassword())) {
            System.out.println("登录失败,用户名或者密码错误" + user);
            return new User();
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        user.setPassword("");
        return user;
    }

    //用户注册
    @PostMapping("/reg")
    public Object reg(String username, String password) {
        User user = null;
        if (username.length() != 11) {
            return new User();
        }
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(PasswordTool.encrypt(password));
            int ret = userMapper.reg(user);
            System.out.println("注册ret:" + ret);
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            user = new User();
        }
        return user;
    }

    //用户登出
    @RequestMapping("/logout")
    public Object logout(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.removeAttribute("user");
            return 200;
        }
        return 500;
    }

    //判断用户是否登录
    @RequestMapping("/isLogin")
    public Object isLogin(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("user") != null) {
            return '1';
        }
        return '0';

    }
}
